package com.ferris.redbook.exception;

import com.ferris.redbook.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.servlet.http.HttpServletRequest; // Spring Boot 3.0使用jakarta
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException e) {
        return AjaxResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        if (!fieldErrors.isEmpty()) {
            FieldError fieldError = fieldErrors.get(0);
            return AjaxResult.badRequest(fieldError.getDefaultMessage());
        }

        return AjaxResult.badRequest("参数错误");
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        e.printStackTrace(); // 打印异常堆栈，方便调试
        return AjaxResult.error("服务器内部错误");
    }

    @ExceptionHandler(FileUploadException.class)
    public AjaxResult handleFileUploadException(FileUploadException e) {
        return AjaxResult.error(400, e.getMessage());
    }
}

